//
//  RegisterViewController.m
//  KiklinkApp
//
//  Created by LF on 14/10/24.
//  Copyright (c) 2014年 Kiklink. All rights reserved.
//

#import "RegisterViewController.h"
#import "API.h"

@interface RegisterViewController()

@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTextField;
@property (weak, nonatomic) IBOutlet UITextField *verificationCodeTextField;
@property (weak, nonatomic) IBOutlet UITextField *nicknameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UITextField *repeatPasswordTextField;
@property (strong, nonatomic) IBOutlet UIView *backgroundView;


@end

@implementation RegisterViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view.
	UITapGestureRecognizer *backgroundTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard)];
	[self.backgroundView addGestureRecognizer:backgroundTapRecognizer];
}

-(void)closeKeyboard
{
	[self.phoneNumberTextField resignFirstResponder];
	[self.verificationCodeTextField resignFirstResponder];
	[self.nicknameTextField resignFirstResponder];
	[self.passwordTextField resignFirstResponder];
	[self.repeatPasswordTextField resignFirstResponder];
}

- (IBAction)omClickGetVerifiactionCode:(id)sender {
	
	if (! [AccountManager isPhoneNumberValid:self.phoneNumberTextField.text]) {
		showAlert(@"手机号格式不正确");
		return;
	}
	
	[AccountManager sendVerificationCodeTo:self.phoneNumberTextField.text];
	
}

- (IBAction)onClickRegister:(id)sender {
	if (! [AccountManager isVerificationCodeValid:self.verificationCodeTextField.text]) {
		showAlert(@"验证码格式不正确");
		return;
	}
	
	if (! [AccountManager isPasswordValid:self.passwordTextField.text]) {
		showAlert(@"密码过短");
		return;
	}
	
	if (! [self.passwordTextField.text isEqualToString:self.repeatPasswordTextField.text]) {
		showAlert(@"密码不一致");
		return;
	}
	
	[API registKiklinkWithPhoneNumber:self.phoneNumberTextField.text verificationCode:self.verificationCodeTextField.text displayName: self.nicknameTextField.text password:self.passwordTextField.text Callback:^(int stateCode, NSString *word, id content) {
		
		if(stateCode == FAILURE_RETURN_ERRER_CODE)
		{
			showAlert(word);
			return;
		}
		else if(stateCode < 0)
		{
			showAlert(@"注册失败");
			return;
		}
		else
		{
			showAlert(@"注册成功");
			
			[AccountManager firstLoginKiklinkWithUsername:self.phoneNumberTextField.text password:self.passwordTextField.text callback:^(int stateCode, NSString *word, id content) {
				
			}];
			[self dismissViewControllerAnimated:YES completion:nil];
		}
		
	}];
}

@end
